package com.android.multiplesmart.utils;



// SpeechTranslationConfig speechTranslationConfig = SpeechTranslationConfig.fromSubscription(speechSubscriptionKey, serviceRegion);
//         speechTranslationConfig.setSpeechRecognitionLanguage("zh-CN");
//         String[] toLanguages = {"it"};
//         for (String language : toLanguages) {
//         speechTranslationConfig.addTargetLanguage(language);
//         }
//
//         try {
//         start(speechTranslationConfig);
//         } catch (InterruptedException e) {
//         e.printStackTrace();
//         } catch (ExecutionException e) {
//         e.printStackTrace();
//         }

import android.util.Log;

import com.android.multiplesmart.DemoApplication;
import com.microsoft.cognitiveservices.speech.ResultReason;
import com.microsoft.cognitiveservices.speech.SpeechConfig;
import com.microsoft.cognitiveservices.speech.SpeechRecognitionEventArgs;
import com.microsoft.cognitiveservices.speech.SpeechRecognizer;
import com.microsoft.cognitiveservices.speech.audio.AudioConfig;
import com.microsoft.cognitiveservices.speech.translation.SpeechTranslationConfig;
import com.microsoft.cognitiveservices.speech.translation.TranslationRecognitionEventArgs;
import com.microsoft.cognitiveservices.speech.translation.TranslationRecognizer;
import com.microsoft.cognitiveservices.speech.util.EventHandler;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

/**
 * @author wangbaoxuan
 * @Class SpeechTransUtils
 * @date 2024-04-08 14:58
 * @Description: 微软翻译工具类
 */
public class SpeechTransUtils {
    private static  SpeechTransUtils  speechTransUtils;
    //语音识别语言-默认中国
    private String  language="zh-CN";//默认中国
    //翻译目标语言-默认意大利
    private String  translation_language="it";//默认意大利
    //音频配置
    private AudioConfig audioConfig;
    //翻译器
    private TranslationRecognizer translationRecognizer;

    private    SpeechRecognizer speechRecognizer;
    //讲话初始化
    private SpeechTranslationConfig speechTranslationConfig;

    private List<String> toLanguages=new ArrayList<>();

    private static String speechSubscriptionKey = "1aae1a3c2fa3435eab6a21ee3ced9e78";

    private static String serviceRegion = "southeastasia";
    public  static SpeechTransUtils  getSpeechTransUtils(){
          if(speechTransUtils==null){
               synchronized (SpeechTransUtils.class){
                    if(speechTransUtils==null){
                        speechTransUtils=new SpeechTransUtils();
                    }
               }
          }
          return  speechTransUtils;
    }

    /**
     * 传输微软翻译的key
     * @param speechSubscriptionKey
     * @param serviceRegion
     * @return
     */
    public SpeechTransUtils key(String speechSubscriptionKey,String serviceRegion){
         this.speechSubscriptionKey=speechSubscriptionKey;
         this.serviceRegion=serviceRegion;
         return  this;
  }


    /**
     * 语音识别语言
     */
    public  SpeechTransUtils setLanguage(String  language){
        this.language=language;
        if (speechTranslationConfig!=null){
            speechTranslationConfig.setSpeechRecognitionLanguage(language);
        }
     return  this;
    }
    /**
     * 翻译目标语言
     */
    public  SpeechTransUtils setTranslationLanguage(List<String>  toLanguages){
        this.toLanguages=toLanguages;
        return  this;
    }
    /**
     * 初始化翻译设置
     */
    public  void  initialize(){
         speechTranslationConfig = SpeechTranslationConfig.fromSubscription(speechSubscriptionKey, serviceRegion);
         speechTranslationConfig.setSpeechRecognitionLanguage(language);
         speechTranslationConfig.setProperty("speech.punctuation.timeout", "2000");
         if(toLanguages.size()<0){
             toLanguages.add(translation_language);
             for (String language : toLanguages) {
                 speechTranslationConfig.addTargetLanguage(language);
             }
         }else {
             for (String language : toLanguages) {
                 speechTranslationConfig.addTargetLanguage(language);
             }
         }
        audioConfig = AudioConfig.fromDefaultMicrophoneInput();
    }


    public  void stop(){
        if (translationRecognizer!=null){
            translationRecognizer.close();
            speechRecognizer.close();
            translationRecognizer=null;
            speechRecognizer=null;
            DemoApplication.getHandlerUtils().saveCrashInfo2File("执行语音关闭");
            System.out.println("JWebSocketClientService执行了语音关闭");
        }
    }




    /**
     * 开始讲话
     * @throws InterruptedException
     * @throws ExecutionException
     */
    public void startSpeech(SpeechCallBack speechCallBack)  {
        //设置使用麦克风

        speechRecognizer = new SpeechRecognizer(speechTranslationConfig, audioConfig);
        translationRecognizer = new TranslationRecognizer(speechTranslationConfig, audioConfig);
        translationRecognizer.startContinuousRecognitionAsync();
        translationRecognizer.recognized.addEventListener(new EventHandler<TranslationRecognitionEventArgs>() {
            @Override
            public void onEvent(Object sender, TranslationRecognitionEventArgs e) {
                if (e.getResult().getReason() == ResultReason.TranslatedSpeech) {///翻译结束并解析
//                    System.out.println("RECOGNIZED: Text="+e.getResult().getText());
                    for (Map.Entry<String, String> pair : e.getResult().getTranslations().entrySet()) {///获取翻译结果
                      //  System.out.printf("Translated into '%s': %s\n", pair.getKey(), pair.getValue());
                        if(speechCallBack!=null){
                            speechCallBack.value(e.getResult().getText(),pair.getValue(),pair.getKey());
                        }
                    }
                }
            }
        });

        translationRecognizer.recognizing.addEventListener(new EventHandler<TranslationRecognitionEventArgs>() {
            @Override
            public void onEvent(Object sender, TranslationRecognitionEventArgs e) {
                for (Map.Entry<String, String> pair : e.getResult().getTranslations().entrySet()) {///获取翻译结果
                    //  System.out.printf("Translated into '%s': %s\n", pair.getKey(), pair.getValue());
                    if(speechCallBack!=null){
                        speechCallBack.valuerecognizing(e.getResult().getText(),pair.getValue(),pair.getKey());
                    }
                }
            }
        });

        speechRecognizer.startContinuousRecognitionAsync();
        speechRecognizer.recognized.addEventListener(new EventHandler<SpeechRecognitionEventArgs>() {
            @Override
            public void onEvent(Object sender, SpeechRecognitionEventArgs e) {
                System.out.println("识别完成"+e.getResult().getText());
                speechCallBack.recognized(e.getResult().getText());
            }
        });

        speechRecognizer.recognizing.addEventListener(new EventHandler<SpeechRecognitionEventArgs>() {
            @Override
            public void onEvent(Object sender, SpeechRecognitionEventArgs e) {
//               if (e.getResult().getReason()==ResultReason.RecognizedSpeech){
                speechCallBack.recognizing(e.getResult().getText());
//               }

            }
        });
    }





    /**
     * 停止讲话
     */
    public void stopSpeech(){
        if (translationRecognizer!=null){
            translationRecognizer.stopContinuousRecognitionAsync();

        }
        if (speechRecognizer!=null){
            speechRecognizer.stopContinuousRecognitionAsync();
            speechRecognizer.stopKeywordRecognitionAsync();
        }

    }

    public   interface  SpeechCallBack{
       void value(String language,String translation_language,String key);
       void valuerecognizing(String language,String translation_language,String key);
       void recognizing(String language);
       void recognized(String language);
    }
}
